package com.gongzonqiang.Interceptor;

import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.gongzonqiang.pojo.User;
import com.gongzonqiang.utils.JsonUtils;
import com.gongzonqiang.utils.ResResult;

/**
 * 管理员拦截器
 * 
 * @author youjie
 *
 */
@Component
public class AdminInterceptor implements HandlerInterceptor {

	@Autowired
	private StringRedisTemplate redisTemplate;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		System.out.println("管理员拦截器................." + request.getRequestURI());
		HttpServletRequest req = (HttpServletRequest) request;
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");
		String token = req.getHeader("token");
		System.out.println(token);
		
		ResResult resResult = new ResResult();

		// token为空
		if (StringUtils.isEmpty(token)) {
			PrintWriter writer = response.getWriter();
			resResult.setStatus(10000);
			resResult.setmessage("空的TOKEN");
			response.setStatus(10000);
			writer.write(JsonUtils.objectToJson(resResult));
			return false;
		}

		// redis中是否还有token
		String userString = redisTemplate.opsForValue().get(token);
		if (userString == null) {
			PrintWriter writer = response.getWriter();
			// 过期或者token错误 客户端因要重新登录
			resResult.setStatus(10000);
			resResult.setmessage("用户没有登录");
			response.setStatus(10000);
			writer.write(JsonUtils.objectToJson(resResult));
			return false;
		}
		redisTemplate.expire(token, 84000, TimeUnit.SECONDS); // 每用一次就更新过期时间为一天

		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
	}

}
